package Sort;

public class MergeSortNor {
    /**
     * 归并排序（非递归）
     * @param
     */

    public static void mergeSortNor(int[] arr){
        int gap=1;
        while (gap<arr.length){
            for (int i = 0; i <arr.length; i+=gap*2) {
                int left=i;
                int mid=left+gap-1;
                if(mid>=arr.length){
                    mid=arr.length-1;
                }
                int right=mid+gap;
                if(right>=arr.length){
                    right=arr.length-1;
                }
                megerTogether(arr,left,mid,right);
            }
            gap*=2;
        }
    }

    public static void megerTogether(int[] arr,int left,int mid,int right){
        int s1=left;
        int e1=mid;
        int s2=mid+1;
        int e2=right;
        int k=0;
        int[] tmp=new int[right-left+1];
        while (s1<=e1&&s2<=e2){
            if (arr[s1]<arr[s2]){
                tmp[k++]=arr[s1++];
            }
            else {
                tmp[k++]=arr[s2++];
            }
        }
        while (s1<=e1){
            tmp[k++]=arr[s1++];
        }
        while (s2<=e2){
            tmp[k++]=arr[s2++];
        }
        for (int i = 0; i <k; i++) {
            arr[i+left]=tmp[i];
        }
    }

    public static void main(String[] args) {
        int[] array={5,1,9,4,3};
        mergeSortNor(array);
        for (int i = 0; i <array.length; i++) {
            System.out.print(array[i]+" ");
        }

    }
}
